package com.witdata.controller.course;

import java.util.List;

import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import com.witdata.common.domain.Result;
import com.witdata.common.domain.Status;
import com.witdata.common.domain.dto.CourseDto;
import com.witdata.common.domain.vo.CourseVo;
import com.witdata.common.exception.GlobalException;
import com.witdata.common.service.course.CourseService;
import com.witdata.common.service.course.CourseUsersService;

import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;


@RestController
@RequiredArgsConstructor
@RequestMapping("/classroom/course")
@Tag(name = "课程管理")
public class CourseController {

    private final CourseService courseService;
    private final CourseUsersService courseUsersService;
    
    @GetMapping("/list/{userId}")
    public Result<List<CourseVo>> getCourseList(@PathVariable("userId") Long userId) {
        return Result.ok(Status.SUCCESS, courseUsersService.getUserCourseList(userId));
    }

    @GetMapping("/detail/{courseId}")
    public Result<CourseVo> getCourseDetail(@PathVariable("courseId") Long courseId) {
        return Result.ok(Status.SUCCESS, courseService.getCourseById(courseId));
    }

    @PostMapping("/create")
    public Result<String> addCourse(@RequestBody CourseVo courseVo) {
        CourseDto courseDto = new CourseDto(courseVo);
        Boolean exists = courseService.createCourse(courseDto);
        courseUsersService.addUser(courseDto.getId(), courseDto.getCreatorId(), 1);
        if (!exists) throw new GlobalException(Status.CREATE_COURSE_FAILED);
        return Result.ok(Status.SUCCESS);
    }
    
    @PutMapping("/update")
    public Result<String> updateCourse(@RequestBody CourseDto courseDto) {
        Boolean exists = courseService.updateCourse(courseDto);
        if (!exists) throw new GlobalException(Status.UPDATE_COURSE_FAILED);
        return Result.ok(Status.SUCCESS);
    }
    
    @DeleteMapping("/delete/{courseId}")
        public Result<String> deleteCourse(@PathVariable("courseId") Long courseId) {
        Boolean exists = courseService.deleteCourse(courseId);
        if (!exists) throw new GlobalException(Status.DELETE_COURSE_FAILED);
        return Result.ok(Status.SUCCESS);
    }

    @PostMapping("/cover/upload")
    public Result<String> uploadCover(@RequestParam("cover") MultipartFile cover) {
        String url = courseService.uploadCover(cover);
        return Result.ok(Status.UPLOADSUCCESS, url);
    }
}
